package org.example.sys.service;

import org.example.sys.bean.TableData;
import org.example.sys.bean.TableData.Pagination;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

public abstract class PageService<T> {

    protected <T> Page<T> pageData(JpaRepository<T, Integer> jpaRepository, Integer pageNo, Integer pageSize, Sort sort) {
        if (pageNo == null)
            pageNo = 0;
        if (pageSize == null)
            pageSize = 0;
        return jpaRepository.findAll(PageRequest.of(Math.max(pageNo, 1) - 1, Math.max(pageSize, 1), sort));
    }

    protected <T> Page<T> pageData(JpaRepository<T, Integer> jpaRepository, Integer pageNo, Integer pageSize, String... properties) {
        return pageData(jpaRepository, pageNo, pageSize, Sort.by(Sort.Direction.DESC, properties));
    }

    protected <T> Page<T> pageData(JpaRepository<T, Integer> jpaRepository, Integer pageNum, Integer pageSize) {
        return pageData(jpaRepository, pageNum, pageSize, "id");
    }

    protected <T> TableData<T> tableData(JpaRepository<T, Integer> jpaRepository, Integer pageNum, Integer pageSize, Sort sort) {
        Page<T> page = pageData(jpaRepository, pageNum, pageSize, sort);
        TableData<T> tableData = new TableData<>();
        tableData.setTableData(page.getContent());
        Pageable pageable = page.getPageable();
        tableData.setPagination(Pagination.builder().total(page.getTotalElements()).currentPage(pageable.getPageNumber() + 1).pageSize(pageable.getPageSize()).build());
        return tableData;
    }

    protected <T> TableData<T> tableData(JpaRepository<T, Integer> jpaRepository, Integer pageNum, Integer pageSize) {
        return tableData(jpaRepository, pageNum, pageSize, Sort.by(Sort.Direction.DESC, "id"));
    }
}
